package com.icss.th.question.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.icss.th.common.util.SecureUtil;
import com.icss.th.question.pojo.Question;
import com.icss.th.question.service.QuestionService;
import com.icss.th.question.service.SimilarQuestionService;

/**
 * Servlet implementation class SimilarQuestionServlet
 */
@WebServlet("/similarQ")
public class SimilarQuestionServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		/**
		*  id = encrypted examID in DB
		*/
		String id = request.getParameter("id");
		/**
		*  typeId = encrypted typeID in DB
		*  Note: if typeId is null, then it will be find after an SQL command. 
		*  But, it is strongly recomended to give a typeId to save resource.
		*/
		String typeId = request.getParameter("typeId");
		int intTypeId = 0;
		
		int[] neighbors = null;
		try 
		{
			id = SecureUtil.decryptPassword(id);
			if (typeId == null)
			{
				Question q = QuestionService.getBrotherQuestion(id, null, null, false);
				intTypeId = q.getTypeId();
				typeId = SecureUtil.encryptPassword(String.valueOf(intTypeId));
			}
			else
			{
				intTypeId = Integer.parseInt(SecureUtil.decryptPassword(typeId));
			}
			neighbors = SimilarQuestionService.getNeighbors(Integer.parseInt(id), intTypeId);
		} 
		catch (Exception e) 
		{
			throw new ServletException(e.getMessage(), e);
		}
		
		if (neighbors == null)
		{ 
			neighbors = new int[50];
		}
		request.setAttribute("encryptedExamID", id);
		request.setAttribute("encryptedTypeID", id);
		request.setAttribute("neighbors", neighbors);
		request.getRequestDispatcher("/detail.jsp").forward(request, response);
	}
}
